import socket
from commands import Commands
from udpNode import UDPNode

class Client:
    def __init__(self):
        self.serverPort = 8988
        self.serverAddress = socket.gethostname()
        self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #ako u 26oj liniji gasis sock_Dgram ovde otvori taj ne Stream?
        self.clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR   , 1)
        self.clientSocket.connect((self.serverAddress, self.serverPort)) 
        self.clientSocket.settimeout(30.0)
        print "CONNECTED TO SERVER"
        self.localPort = self.clientSocket.getsockname()[1]
        print self.localPort
        self.clientSocket.send(Commands.NEW_NODE)
        self.opseg = self.read_line(self.clientSocket) 
        self.lastClients = []
        while True:
            address = self.read_line(self.clientSocket)
            print address
            if address.strip() == "#FINISHED_SENDING_LAST_CLIENTS$":
                break
            port = self.read_line(self.clientSocket)
            self.lastClients.append([address.strip(), port.strip()])
        print self.lastClients
        self.clientSocket.close()
        print "MOJ PORT: ", self.localPort
        
        udpn = UDPNode(self.opseg, self.localPort, self.lastClients)
        udpn.start()
        
    def read_line(self, s):
        ret = ''
        while True:
            try:
                
                c = s.recv(1)
                if c == '\n' or c == '':
                    break
                else:
                    ret += c
            except socket.timeout:
                print "READ TIMEOUT"
                return ""
        return ret

Client()
        
        
    
